﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Spring.Aop.Framework;
using Spring.Aop.Target;

namespace dotUML.System
{
    /// <summary>
    /// This class is used to instrument objects with Spring.Net AOP.
    /// Logging advices are added to all methods of instrumented classes.
    /// </summary>
    public static class InstrumentationManager
    {
        /// <summary>
        /// Instrument an object.
        /// </summary>
        /// <param name="ObjectToInstrument">Object to be instrumented.</param>
        /// <param name="InstrumentationType">Type of instrumentation.</param>
        /// <returns>Instrumented object.</returns>
        public static object InstrumentObject(Object ObjectToInstrument, EInstrumentationType InstrumentationType)
        {
            try
            {
                ProxyFactory factory = GetProxyFactory(ObjectToInstrument);
                InstrumentProxy(factory, InstrumentationType);
                return factory.GetProxy();
            }
            catch (Exception ex)
            {
                throw new dotUMLException(String.Format(Resources.InstrumentationManager_InstrumentObject_Exception, ObjectToInstrument.GetType().Name), ex);
            }
        }

        /// <summary>
        /// Create a ProxyFactory for an object.
        /// </summary>
        /// <param name="ProxiedObject">Object to be instrumented.</param>
        /// <returns>Proxy factory.</returns>
        private static ProxyFactory GetProxyFactory(Object ProxiedObject)
        {
            ProxyFactory result = new ProxyFactory(ProxiedObject);
            return result;
        }

        /// <summary>
        /// Assign advices to a proxy factory.
        /// </summary>
        /// <param name="Proxy">Proxy factory.</param>
        /// <param name="InstrumentationType">Type of instrumentation.</param>
        private static void InstrumentProxy(ProxyFactory Proxy, EInstrumentationType InstrumentationType)
        {
            switch (InstrumentationType)
            {
                case EInstrumentationType.Logging:
                    Proxy.AddAdvice(new Aspects.LoggingBeforeAdvice());
                    Proxy.AddAdvice(new Aspects.LoggingAfterAdvice());

                    break;
                default:
                    break;
            }
        }
        
    }
}
